package com.chenxin.wms.process.outbound.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.common.annotation.WmsLogs;
import com.chenxin.common.constant.WmsConstants;
import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.common.enums.WmsBusinessStatus;
import com.chenxin.common.enums.WmsTaskSubType;
import com.chenxin.common.enums.WmsTaskType;
import com.chenxin.common.exception.wms.WmsException;
import com.chenxin.common.utils.StringUtils;
import com.chenxin.wms.domain.ObDetailEntity;
import com.chenxin.wms.domain.TaskEntity;
import com.chenxin.wms.domain.WcsTaskEntity;
import com.chenxin.wms.mapper.ObDetailMapper;
import com.chenxin.wms.mapper.TaskMapper;
import com.chenxin.wms.process.outbound.IProcObDetailExecutor;
import com.chenxin.wms.process.task.IWcsTaskProcess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ProcObDetailExecutor implements IProcObDetailExecutor {
    @Autowired
    private ObDetailMapper obDetailMapper;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private IWcsTaskProcess wcsTaskProcess;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @WmsLogs(name = "出库明细执行出库")
    public ProcResult call(Long obDetailId, Long creator) {
        // 根据明细ID获取所需信息（明细、主单、物料等）
        if (StringUtils.isNull(obDetailId)) {
            return ProcResult.error("executor_err001", "明细ID不能为空");
        }
        ObDetailEntity obDetail = obDetailMapper.selectById(obDetailId);
        if (obDetail == null) {
            return ProcResult.error("executor_err002", "明细ID【" + obDetailId + "】不存在");
        }
        if (obDetail.getObDetailStatus() > WmsBusinessStatus.OB_DETAIL_PREPARED.getCode()) {
            return ProcResult.error("executor_err003", "明细【" + obDetailId + "】当前状态【" + obDetail.getObDetailStatus() + "】无法执行出库");
        }
        // 检索明细对应备货任务（初始状态的任务允许执行）
        QueryWrapper<TaskEntity> preTaskQW = new QueryWrapper<>();
        preTaskQW.lambda().eq(TaskEntity::getDetailId, obDetailId)
                .eq(TaskEntity::getMasterId, obDetail.getObMasterId())
                .eq(TaskEntity::getTaskType, WmsTaskType.SHIPMENT_OUT.getCode())
                .eq(TaskEntity::getTaskSubType, WmsTaskSubType.PREPARE_OUT.getCode())
                .eq(TaskEntity::getTaskStatus, WmsConstants.TASK_STATUS_INIT);
        List<TaskEntity> execTasks = taskMapper.selectList(preTaskQW);
        if (execTasks == null || execTasks.size() == 0) {
            return ProcResult.error("executor_err004", "明细【" + obDetailId + "】不存在可出库的任务");
        }
        // 循环执行相关任务
        for (TaskEntity exeTask : execTasks) {
            // 获取起始位置
            String fromPosition = exeTask.getFromPosition();
            String zoneType = "A";
            // 判断起始位置所属仓库与对应出库站台
            String toPosition = "临时出库站台";
            String stationNo = "作业站台";
            exeTask.setToPosition(toPosition);
            // 更新任务状态
            exeTask.setTaskStatus(WmsConstants.TASK_STATUS_EXEC);
            exeTask.setStationNo(stationNo);
            exeTask.setUpdater(creator);
            exeTask.setUpdateDate(new Date());
            int taskRows = taskMapper.updateById(exeTask);
            if (taskRows <= 0) {
                throw new WmsException("executor_err006", "任务【" + exeTask.getTaskId() + "】更新失败");
            }

            // 根据起始位置的zone_type是否属于自动库区来判断是否需要下发设备任务
            if (WmsConstants.ZONE_TYPE_A.equals(zoneType)) {
                WcsTaskEntity wcsTask = new WcsTaskEntity();
                // 以时间戳作为requestPk
                wcsTask.setRequestPk(String.valueOf(System.currentTimeMillis()));
                wcsTask.setContNo(exeTask.getFromContNo());
                wcsTask.setTrkType(WmsTaskType.SHIPMENT_OUT.getCode());
                wcsTask.setFrmPos(fromPosition);
                wcsTask.setToPos(toPosition);
                wcsTask.setCurPos(fromPosition);
                wcsTask.setTrkStatus(WmsConstants.TASK_STATUS_INIT);
                wcsTask.setCreator(creator);
                wcsTask.setCreateDate(new Date());
                Long trkId = wcsTaskProcess.procWmsToWcsInsert(wcsTask);
            }
            // 更新明细状态
            obDetail.setObDetailStatus(WmsBusinessStatus.OB_MASTER_EXEC.getCode());
            obDetail.setComments("明细【" + obDetailId + "】已执行出库任务");
            obDetail.setUpdater(creator);
            obDetail.setUpdateDate(new Date());
            int detailRows = obDetailMapper.updateById(obDetail);
            if (detailRows <= 0) {
                throw new WmsException("executor_err007", "明细【" + obDetailId + "】更新失败");
            }
        }
        return ProcResult.success("明细【" + obDetailId + "】出库执行成功！所属主单【" + obDetail.getObMasterId() + "】");
    }
}
